import React, { useState, useEffect } from 'react'
import { Tabs, Affix, Button, Select, Radio, Form, Row, Col, InputNumber, Spin, message } from 'antd'
import { udConfigProvider, UdFormItem, UdNumberRange, http } from '@/lib'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import './style.scss'
import { formUtils } from '@/lib/utils/formUtils'
import ControlTitle from '../ControlTitle'
import apis from '@/apis/SystemSettings'

enum EInventoryType {
  // 月末前
  END_OF_MONTH = 'ENDOFMONTH',
  // 每月
  ONCE_A_MONTH = 'ONCEAMONTH',
  // 每周
  WEEKLY = 'WEEKLY',
}
const { TabPane } = Tabs
const { Option } = Select
let currentBrand = ''

function InventoryTimeControl(props: IInventoryTimeControlProps) {
  const { tabs, form } = props
  const { getFieldDecorator } = form
  const pageContainer = udConfigProvider.ui.getPageContainer()
  const [data, setData] = useState<any>({})
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    let code = tabs && tabs[0] ? tabs[0].value : undefined
    code && getData(code)
    return () => {
      setData({})
    }
  }, [tabs[0]])
  const saveHandle = () => {
    form.validateFieldsAndScroll((error, values) => {
      console.log(values)
      const submitData = formUtils.handleValues(values)
      if (!error && validateInventoryField(submitData)) {
        const brandName = tabs.find(tab => tab.value === currentBrand).title.slice(4, 6)
        const params: any = {brandCode: currentBrand, brandName, ...submitData}
        if (data.id) {
          // 修改
          params.id = data.id
        }
        setLoading(true)
        http.post(apis.UpdateInventoryDate, params).then(res => {
          message.success('操作成功')
        }).finally(() => setLoading(false))
      }
    })
  }
  const getData = (key) => {
    currentBrand = key
    setLoading(true)
    const params = { brandCode: key }
    http.get(apis.InventoryDetail, { params }).then(res => {
      const data = res.data[0] || {}
      const result = {
        ...data,
        inventoryType: data.inventoryType || undefined,
        dateNum: data.dateNum || undefined,
        monthStartTime: data.monthStartTime || undefined,
        monthEndTime: data.monthEndTime || undefined,
        weeklyNum: data.weeklyNum || undefined,
      }
      setData(result)
      formUtils.setValues(form, [{id: 'inventoryType'}, {id: 'dateNum'}, {id: ['monthStartTime', 'monthEndTime']}, {id: 'weeklyNum'}], result)
    }).catch(() => {
      formUtils.setValues(form, [{id: 'inventoryType'}, {id: 'dateNum'}, {id: ['monthStartTime', 'monthEndTime']}, {id: 'weeklyNum'}], {})
    }).finally(() => setLoading(false))
  }

  const inventoryTypeChange = (e) => {
    // 切换判断时间类型置空所有数据
    formUtils.setValues(form, [{id: 'dateNum'}, {id: ['monthStartTime', 'monthEndTime']}, {id: 'weeklyNum'}], {})
  }

  const radioOptions = [
    {
      label: '月末前',
      value: EInventoryType.END_OF_MONTH,
    },
    {
      label: '每月',
      value: EInventoryType.ONCE_A_MONTH,
    },
    {
      label: '每周',
      value: EInventoryType.WEEKLY,
    },
  ]

  const weekOptions = [
    {
      title: '周一',
      value: 1,
    },
    {
      title: '周二',
      value: 2,
    },
    {
      title: '周三',
      value: 3,
    },
    {
      title: '周四',
      value: 4,
    },
    {
      title: '周五',
      value: 5,
    },
    {
      title: '周六',
      value: 6,
    },
    {
      title: '周日',
      value: 7,
    },
  ]

  let footer = <div className='detail-footer'><Button type="primary" onClick={saveHandle}>保存</Button></div>
  if (pageContainer) {
    footer = (
      <Affix offsetBottom={0} target={() => pageContainer}>
        {footer}
      </Affix>
    )
  }
  return (
    <>
      <ControlTitle title='手工盘点时间控制' desc='用于控制片区人员操作“手工盘点”功能的开放权限' />
      <Tabs type='card' onChange={getData}>
        {tabs.map(({ value, title }) => (
          <TabPane tab={title} key={value}>
            <Spin spinning={loading}>
              <Form className='general-config-form inventory-time-form'>
                <Row className='inventory-form-body'>
                  <Col className='left-type-row'>
                    <UdFormItem id='inventoryType' label='选择盘点时间' form={form} getFieldDecorator={getFieldDecorator} render={<Radio.Group onChange={inventoryTypeChange} options={radioOptions} />} />
                  </Col>
                  <Col>
                    <Row className='right-value-row'>
                      <Col>
                        <div className='item'>
                          <UdFormItem id='dateNum' form={form} getFieldDecorator={getFieldDecorator} render={<InputNumber placeholder='请输入天数' max={31} min={1} />} />
                          <span className='addon-after'>天</span>
                        </div>
                        <div className='item number-range'>
                          <UdFormItem id={['monthStartTime', 'monthEndTime']} form={form} getFieldDecorator={getFieldDecorator} render={<UdNumberRange begin={{min: 1, max: 31, formatter: value => value && `${value}号`, parser: value => value.replace('号', '')}} end={{min: 1, max: 31, formatter: value => value && `${value}号`, parser: value => value.replace('号', '')}} />} />
                        </div>
                        <div className='item'>
                          <UdFormItem id='weeklyNum' form={form} getFieldDecorator={getFieldDecorator}
                            render={
                              <Select placeholder='请选择时间'>
                                {weekOptions.map(({ title, value }) => <Option key={value} value={value}>{title}</Option>)}
                              </Select>
                            }
                          />
                        </div>
                      </Col>
                    </Row>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </TabPane>
        ))}
      </Tabs>
      {footer}
    </>
  )
}

export default React.memo(Form.create<IInventoryTimeControlProps>()(InventoryTimeControl))

interface IInventoryTimeControlProps {
  form: WrappedFormUtils
  tabs: { value: string, title: string }[]
}

function validateInventoryField(values) {
  const isEndMonth = () => values.inventoryType === EInventoryType.END_OF_MONTH
  const isOnceMonth = () => values.inventoryType === EInventoryType.ONCE_A_MONTH
  const isWeekly = () => values.inventoryType === EInventoryType.WEEKLY
  if (isEndMonth() && (values.dateNum === null || values.dateNum === undefined)) {
    message.error('请输入盘点时间')
    return false
  }
  if (isOnceMonth()) {
    if (values.monthStartTime === null || values.monthStartTime === undefined) {
      message.error('请输入盘点开始时间')
      return false
    }
    if (values.monthEndTime === null || values.monthEndTime === undefined) {
      message.error('请输入盘点结束时间')
      return false
    }
    if (values.monthStartTime > values.monthEndTime) {
      message.error('盘点开始时间不能大于结束时间')
      return false
    }
  }
  if (isWeekly() && (values.weeklyNum === null || values.weeklyNum === undefined)) {
    message.error('请选择盘点时间')
    return false
  }
  return true
}
